package com.xuanzheng.company.filter;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.CompanyEmployeeService;
import com.xuanzheng.company.service.impl.CompanyEmployeeServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 此过滤器用于限制未加入公司的用户访问某些功能
 * 只有"加入公司"和"个人资料"功能是用户在未加入公司时可以访问的
 * 适用于普通用户和企业负责人
 */
@WebFilter(urlPatterns = {
    "/clockIn", "/getClockRecords", "/getTasks", "/getPerformance",
    "/submitTask", "/getAnnouncements"
})
public class FeatureAccessFilter implements Filter {
    private final CompanyEmployeeService companyEmployeeService = new CompanyEmployeeServiceImpl();
    private final Gson gson = new Gson();
    
    // 不需要检查的路径
    private final List<String> excludedPaths = Arrays.asList(
        "/getCompanies", "/checkJoinCompanyStatus", "/submitJoinCompany",
        "/getCurrentUser", "/logout"
    );
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        // 获取请求路径
        String requestURI = httpRequest.getRequestURI();
        String contextPath = httpRequest.getContextPath();
        String path = requestURI.substring(contextPath.length());
        
        // 检查是否是排除的路径
        for (String excludedPath : excludedPaths) {
            if (path.equals(excludedPath)) {
                chain.doFilter(request, response);
                return;
            }
        }
        
        // 获取会话
        HttpSession session = httpRequest.getSession(false);
        
        if (session == null) {
            // 未登录，返回错误信息
            sendErrorResponse(httpResponse, "您尚未登录，请先登录");
            return;
        }
        
        // 获取用户对象
        Object userObj = session.getAttribute("user");
        if (userObj == null || !(userObj instanceof User)) {
            // 用户信息不存在，返回错误信息
            sendErrorResponse(httpResponse, "会话已过期，请重新登录");
            return;
        }
        
        User user = (User) userObj;
        
        // 对普通用户和企业负责人进行限制
        if (user.getRole() == 0 || user.getRole() == 1) {
            // 检查用户是否已加入公司
            boolean canUseFeatures = companyEmployeeService.canUseFeatures(user.getId());
            
            if (!canUseFeatures) {
                // 用户未加入公司，返回错误信息
                sendErrorResponse(httpResponse, "您需要先加入公司才能使用此功能");
                return;
            }
        }
        
        // 继续过滤器链
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
    
    /**
     * 发送错误响应
     */
    private void sendErrorResponse(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", message);
        
        PrintWriter out = response.getWriter();
        out.write(gson.toJson(result));
        out.flush();
    }
} 